import { useEffect, useState } from "react"
import callFeedback from "@/components/common/modalFeedback"
import { BASE_PATH,API } from '@/config'
import { AutoCenter, Button, Grid, Space,Modal,Toast } from "antd-mobile"
import { navigateTo, checkENV2, triggerAppShare, } from "@/utils"
import requewt from "@/utils/requewt"
import GameResult from "@/components/common/modalFeedback/game.result";
import { useToolbar } from "@/components/common/toolbar/hooks"
import useApp from "@/stores/useApp"
import Router from "next/router"
const Puzzel = () => {
    const [theme,setTheme] = useState({})
    const [active, setActive] = useState()
    const { handleGameSuccess } = useToolbar()
    const setVisible = useApp(state=>state.updateShareVisible)
    const handler = {
        finish: async () => {
          const options = {
            method: `POST`,
            headers: {"Content-Type": "multipart/form-data"},
            body: {"answer": active},
          }
          const resp = await requewt(API.game.finish, options);
          const { status,next_paper,remain_draw_num,remain_paper_num } = resp?.data ||{}
  
          // 回答错误
          if(status === 0) {
            const actions = <Button shape="rounded" key={`confirm`} onClick={async e => {
              const env = await checkENV2();
              if (env === `app`) await triggerAppShare()
              else {
                setVisible(true)
              }

              const resp = await requewt(API.user.share);
              if (resp?.error_code !== 0) return;
              // Toast.show({content: `分享成功`});
              c.close();
              
              
              setTimeout(() => {
                setVisible(false)
                const c = callFeedback({
                  bodyClassName: 'price-result-modal rule-modal price-result-modal act-feedback-modal',
                  // title: <div style={{fontWeight:'bold',fontSize:'2rem'}}>分享成功</div>,
                  content: (
                    <GameResult 
                    title={<div style={{fontWeight:'bold',fontSize:'2rem',marginTop:30}}>分享成功</div>}
                      content={<div className="result-modal">
                        <div className="result-modal-text">
                          
                          {
                            <div style={{marginTop:'20px',textIndent:0}}>答题机会+1</div>
                          }
                        </div>
                    </div>}
                    />
                  ),
                  onClose:() => {
                    console.log('close')
                  },
                  actions: [
                    <Button key={`confirm`} onClick={async e => {
                      c.close()
                      handler.play().then(({data}) => {
                        if (!data) {
                          navigateTo('/landing')
                        }
                        setActive('')
                        setTheme(data||{})
                      })
                      // navigateTo('/game')
                    }}  className="act-btn act-btn-bevel">确定</Button>,
                  ],
                  closeOnAction: false,
                  closeOnMaskClick: false,
                
                })
              }, 3000);
              
            }}  className="act-btn act-btn-bevel ">去分享</Button>
           const c =  callFeedback({
              title: <div></div>,
              bodyClassName: 'price-result-modal rule-modal price-result-modal act-feedback-modal',
              
              content: <Space direction="vertical" justify="center" style={{marginTop:'20px',width:'100%'}}>
                <AutoCenter><img className="result-icon" width={48} src={`${BASE_PATH}/img/game/result-fail-icon.png`} /></AutoCenter>
                <AutoCenter style={{fontWeight:'bold'}}>很遗憾回答错误</AutoCenter>
                <AutoCenter>分享成功可重新作答，解锁抽奖机会</AutoCenter>
              </Space>,
              onClose:() => {
                console.log('close')
                handler.play(true).then(({data}) => {
                  if (!data) {
                    navigateTo('/landing')
                  }
                  setActive('')
                  setTheme(data||{})
                })
              },
              actions,
              closeOnAction: false,
              closeOnMaskClick: false,
            })
          // 回答正确
          } else if (status === 1) {
            // 回答正确，还有下一题
            if (next_paper === 1) {
              handleGameSuccess({
                next_paper,remain_draw_num,
                message:theme.tip,
                onCancel() {
                  handler.play().then(({data}) => {
                    // console.log(resp)
                    if (!data) {
                      navigateTo('/landing')
                    }
                    setTheme(data ||{})
                    
                  })
                },
                onConfirm() {
                  Router.replace('/wheel')
                }
              })
              // 回答正确，没有下一题
            } else {
              handleGameSuccess({
                next_paper,remain_draw_num,
                message: theme.tip,
                onCancel() {
                  // handler.play().then(({data}) => {
                  //   // console.log(resp)
                  //   if (!data) {
                  //     navigateTo('/landing')
                  //   }
                  //   setTheme(data ||{})
                    
                  // })
                },
                onConfirm() {
                  Router.replace('/wheel')
                }
              })
              // const c = callFeedback({
              //   bodyClassName: 'act-feedback-modal close-hidden',
              //   title: <img className="result-icon" src={`${BASE_PATH}/img/game/result-success-icon.png`} />,
              //   onClose: () => {
              //     // navigateTo('/landing')
              //   },
              //   content: <div style={{marginTop:'20px'}}>
              //     <AutoCenter><span style={{fontWeight:'bold'}}>恭喜您回答正确！</span></AutoCenter>
              //     <AutoCenter>抽奖机会+1</AutoCenter>
              //     <AutoCenter>今日3题已作答完毕</AutoCenter>
              //   </div>,
              //   actions: <AutoCenter><Button shape="rounded" key="share" className="act-btn act-btn-bevel " onClick={async e => {
              //     c.close()
              //     navigateTo(`/wheel`)
                  
              //       }}>去抽奖</Button></AutoCenter>,

              // closeOnAction: false,
              // closeOnMaskClick: false,
              // })
            }
          }
          setActive('')
          // const m = 
          // const 
          // if (status === '2') {
          //   return  handleSuccess()
          // }

        },
        play: async (hideTip) => {
          Toast.show({icon: 'loading', content: '加载中', duration: 0, maskClickable: false})
          const resp = await requewt(API.game.start,{method: 'post'});
          // alert(resp?.error_code);
          Toast.clear()
          
          if (resp?.error_code == 1011&&!hideTip) {
            console.log("需要去分享")
            const c = callFeedback({
              // title: <div dangerouslySetInnerHTML={{__html: resp?.msg || `失败`}} />,
              bodyClassName: 'price-result-modal rule-modal price-result-modal act-feedback-modal',
              content: <GameResult 
                content={
                  <div className="result-modal">
                    <div className="result-modal-text" style={{marginTop: 30}} >
                      {/* <AutoCenter>很遗憾回答错误...</AutoCenter> */}
                      <AutoCenter>{resp?.msg||'失败'}</AutoCenter>
                    </div>
            </div>
                }
              />
              
              ,
              // content: <ResultComp 
              // content={
              //   ,
              actions: <Grid columns={2} gap={10} >
                <Grid.Item style={{padding: '0 10px'}}>
                <Button shape="rounded" key="share" className="act-btn act-btn-bevel" onClick={async e => {
                  c.close()
                  history.go(-1)
                  
                    }}>返回首页</Button>
                
                </Grid.Item>
                <Grid.Item>
                <Button shape="rounded" key={`confirm`} onClick={async e => {
                  const env = await checkENV2();
                  if (env === `app`) await triggerAppShare()
                  else {
                    setVisible(true)
                  }
    
                  const resp = await requewt(API.user.share);
                  if (resp?.error_code !== 0) return;
                  // Toast.show({content: `分享成功`});
                  c.close();
                  setActive('')
                  setTimeout(() => {
                    handler.play().then(({data}) => {
                      if (!data) {
                        navigateTo('/landing')
                      }
                      setTheme(data||{})
                    })
                  },2000)
                }}  className="act-btn act-btn-bevel ">去分享</Button>
                </Grid.Item>
              </Grid>,
              closeOnAction: false,
              closeOnMaskClick: false,
            })
            return {}
          }
          if (resp?.msg == "ok") {
            return resp
          }else{
            // return Toast.show({content: resp?.msg || `请求游戏失败`,})
          //   const c = callFeedback({
          //     bodyClassName: 'act-feedback-modal close-hidden',
          //   title: <img className="result-icon" src={`${BASE_PATH}/img/game/result-success-full.png`} />,
          //   content: (
          //     <GameResult 
          //       content={<div className="result-modal">
          //         <div className="result-modal-text" style={{marginTop: 30}} dangerouslySetInnerHTML={{__html: resp?.msg || `失败`}}></div>
          //     </div>}
          //     />
          //   ),
          //   actions: [
          //     <Button key={`confirm`} onClick={async e => {
          //       c.close();
          //     }} className="act-btn act-btn-bevel">确 定</Button>,
          //   ],
          //   closeOnAction: false,
          //   closeOnMaskClick: false,
          // })
          
          }
          return {}
        },
        
        sendEnd: ()=> {
          // console.log(window.phase, phase);
          if (window.phase === "playing") {
            au.current.pause();
            end();
          }
        },

      }
    const handleSelect = (answer) => {
      setActive(answer)
    }
    useEffect(() => {
      handler.play().then(({data}) => {
        // console.log(resp)
        if (!data) {
          navigateTo('/landing')
        }
        setTheme(data ||{})
      })
      return () => {
        Toast.clear();
        Modal.clear()
      }
    }, [])
    
    return (
        <div className="puzzle-game-container">
            <div id="game">
              <AutoCenter style={{margin: '20px 30px',fontWeight:'bold'}}>{theme.question}</AutoCenter>
              <Space direction="vertical" justify="center" className="game-theme">
                <div className={active === theme.option_a? "game-theme-item active": "game-theme-item"}  onClick={()=>handleSelect(theme.option_a)}>{theme.option_a}</div>
                <div className={active === theme.option_b? "game-theme-item active": "game-theme-item"} onClick={()=>handleSelect(theme.option_b)}>{theme.option_b}</div>
                <div className={active === theme.option_c? "game-theme-item active": "game-theme-item"} onClick={()=>handleSelect(theme.option_c)}>{theme.option_c}</div>
                
              </Space>
              <AutoCenter style={{marginTop: '20px'}}>
                <Button className="act-btn act-btn-bevel" style={{zIndex:99999}} onClick={handler.finish}>确 定</Button>
              </AutoCenter>
              
        </div>
        <img 
                src={`${BASE_PATH}/img/game/game-icon.png`}
                width='257'
                className="game-icon-2"
              />
            {/* <PuzzleGame times={Math.round(countdown/1000)} onSuccess={handleSuccess} /> */}
        </div>
    )
}

export default Puzzel
